package com.qidian.mes.sys.service.impl;

import com.qidian.mes.pojo.Dict;
import com.qidian.mes.pojo.DictItem;
import com.qidian.mes.sys.mapper.DictItemMapper;
import com.qidian.mes.sys.service.DictItemService;
import com.qidian.mes.util.dot.PagerDTO;
import com.qidian.mes.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Description
 * @Time 2024/4/3 16:35
 */
@Service
public class DictItemServiceImpl implements DictItemService {
    @Autowired
    private DictItemMapper dictItemMapper;
    @Override
    public QdResult<PagerDTO<DictItem>> queryByPage(DictItem dictItem, int page, int limit) {
        PagerDTO<DictItem> pagerDTO = new PagerDTO<>();
        pagerDTO.setData(dictItemMapper.selectByPage(dictItem, (page - 1) * limit, limit));
        pagerDTO.setPage(page);
        pagerDTO.setLimit(limit);
        pagerDTO.setTotal(dictItemMapper.selectCount(dictItem));
        return QdResult.success(pagerDTO);
    }

    @Override
    public QdResult<DictItem> queryById(Long dictItemId) {
        return QdResult.success(dictItemMapper.selectById(dictItemId));
    }

    @Override
    public QdResult deletes(Long[] dictItemIds) {
        dictItemMapper.deleteByIds(dictItemIds);
        return QdResult.success();
    }

    @Override
    public QdResult delete(Long dictItemId) {
        dictItemMapper.deleteDictItem(dictItemId);
        return QdResult.success();
    }

    @Override
    public QdResult updateDict(DictItem dictItem) {
        return  QdResult.isSuccess(dictItemMapper.updateDictItem(dictItem));
    }

    @Override
    public QdResult saveDict(DictItem dictItem) {
        if(dictItem.getDictItemId() == null)
            return QdResult.error();
        // 校验重复
        List<DictItem> dictItems = dictItemMapper.selectByTag(dictItem.getDictType(), dictItem.getDictItemTag());
        if(dictItems != null && dictItems.size() > 0 && !dictItems.get(0).getDictItemId().equals(dictItem.getDictItemId())){
            return QdResult.duplicate("字典项标签重复");
        }
        dictItems = dictItemMapper.selectByValue(dictItem.getDictType(), dictItem.getDictItemValue());
        if(dictItems != null && dictItems.size() > 0 && !dictItems.get(0).getDictItemId().equals(dictItem.getDictItemId())){
            return QdResult.duplicate("字典项数值重复");
        }
        return QdResult.isSuccess(dictItemMapper.insertDictItem(dictItem));
    }
}
